//
//  UserAccountViewModel.swift
//  Sina(微博)
//
//  Created by mac on 15/12/14.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit
import AFNetworking



class UserAccountViewModel: NSObject {
    var userSccount: UserAccount?
    override init() {
        userSccount = UserAccount.loadAccount()
        super.init()
    }
    var userLogin: Bool {
        return userSccount?.access_token != nil
        
    }
     func LoadAccessToken(code: String, finished: (isSuccess: Bool) ->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        AFN.POST(urlString, parameters: parameters, progress: { (p) -> Void in
            
            }, success: { (_ , result) -> Void in
                if let dict = result as? [String : AnyObject] {
                    let userAccount = UserAccount(dict: dict)
                    self.loadUserInfo(userAccount, finished: finished)
                    
                }
                
            }) { (_ , error) -> Void in
                finished(isSuccess: false)
        }
        
    }
    private func loadUserInfo(account: UserAccount,finished: (isSuccess: Bool) ->()) {
        let urlString = "https://api.weibo.com/2/users/show.json"
        if let token = account.access_token,userId = account.uid {
            let parameters = ["access_token": token,"uid": userId]
            let AFN = AFHTTPSessionManager()
            AFN.GET(urlString, parameters: parameters, progress: { (_) -> Void in
                
                }, success: { (_ , result) -> Void in
                    if let dict = result {
                        let avatar_large = dict["avatar_large"] as! String
                        let name = dict["name"] as! String
                        account.name = name
                        account.avatar_large = avatar_large
                        account.saveAccount()
                        finished(isSuccess: true)
                    }
                }, failure: { (_, error) -> Void in
                    finished(isSuccess: false)
            })
            
        }
    }
    
}

